package com.hltx.controller.personaladdress;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.address.Address;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.user.User;
import com.hltx.resolver.DefiniteException;
import com.hltx.service.adress.AddressManager;
import com.hltx.util.ResultInfo;
/**
 * 个人地址controller
 *
 */
@Controller
@RequestMapping("/address")
public class AddressController extends BaseController{
	
	@Resource(name="addressService")
	private AddressManager addressService;
	
	/**
	 * 打开个人地址页面
	 */
	@RequestMapping
	public String index() {
		return "user/address";
	}
	
	/**
	 * 打开个人地址页面
	 */
	@RequestMapping(value="/buyNow")
	public String buyNow(HttpServletRequest request) {
		request.setAttribute("addressId", request.getParameter("addressId"));
		request.setAttribute("goodsId", request.getParameter("goodsId"));
		request.setAttribute("spec", request.getParameter("spec"));
		request.setAttribute("buyNum", request.getParameter("buyNum"));
		request.setAttribute("type", request.getParameter("type"));
		return "user/buy_address";
	}
	
	/**
	 * 异步加载个人地址信息
	 * */
	@RequestMapping(value = "/addressList",method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Map<String, Object> addressList(Page page, HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "查询个人地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			User user=(User) request.getSession().getAttribute("sessionUser");
			page.getParams().put("userid", user.getId());
			List<Address> addressList=addressService.getAddressList(page);
			resMap.put("addressList", addressList);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 打开个人地址页面
	 */
	@RequestMapping(value ="/addAddress")
	public String addAddress(HttpServletRequest request) {
		request.setAttribute("goodsId", request.getParameter("goodsId"));
		request.setAttribute("spec", request.getParameter("spec"));
		request.setAttribute("buyNum", request.getParameter("buyNum"));
		request.setAttribute("type", request.getParameter("type"));
		return "user/shippingAddress";
	}
	
	/**
	 * 添加/修改地址信息
	 * */
	@RequestMapping(value = "/addSave",method = { RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> addSave(Page page, HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "添加/修改个人地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		User user=(User) request.getSession().getAttribute("sessionUser");
		try {
			if(page.getParams().get("addressID")!=null && page.getParams().get("addressID")!=""){
				String city=(String) page.getParams().get("cityid");
				if(city==null || city==""){
					if(page.getParams().get("cityIDList")!=null && page.getParams().get("cityIDList")!=""){
						String cityIDList=(String) page.getParams().get("cityIDList");
						String [] arry=cityIDList.split(",");
						page.getParams().put("provinceID", arry[0]);
						page.getParams().put("cityID", arry[1]);
						page.getParams().put("countryID", arry[2]);
					}
				}else{
					String [] arry=city.split(",");
					page.getParams().put("provinceID", arry[0]);
					page.getParams().put("cityID", arry[1]);
					if (arry.length>=3) {
						page.getParams().put("countryID", arry[2]);
					}
					
				}
				System.out.println("是否设为默认地址："+page.getParams().get("status"));
				if("1".equals(page.getParams().get("status"))){
					page.getParams().put("userid", user.getId());
					addressService.updateDefault(page);
				}
				resMap.put("addressId", page.getParams().get("addressID"));
				addressService.updateAddress(page);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "修改成功!"));
			}else{
				page.getParams().put("userid", user.getId());
				String city=(String) page.getParams().get("cityid");
				String [] arry=city.split(",");
				page.getParams().put("provinceID", arry[0]);
				page.getParams().put("cityID", arry[1]);
				if (arry.length>=3) {
				page.getParams().put("countryID", arry[2]);
				}
				System.out.println("是否设为默认地址111："+page.getParams().get("status"));
                if("1".equals(page.getParams().get("status"))){
                	addressService.updateDefault(page);	
				}
                System.out.println("商品id222为："+page.getParams().get("goodsId"));
                if(!"".equals(page.getParams().get("goodsId"))&&page.getParams().get("goodsId")!=null){
                	Address address=new Address();
                	address.setUserID(user.getId());
                	address.setProvinceID(Integer.valueOf((String)page.getParams().get("provinceID")));
                	address.setCityID(Integer.valueOf((String)page.getParams().get("cityID")));
                	address.setCountryID(Integer.valueOf((String)page.getParams().get("countryID")));
                	address.setReceiverName((String)page.getParams().get("deliveryName"));
                	address.setReceiverPhone((String)page.getParams().get("deliveryPhone"));
                	address.setReceiverAddress((String)page.getParams().get("addressDetail"));
                	address.setStatus(Integer.valueOf((String)page.getParams().get("status")));
                	addressService.addSaveId(address);
                	System.out.println("新添加的个人地址id为："+address.getId());
                	resMap.put("addressId", address.getId());
                }else{
                	addressService.addSave(page);
                }
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "添加成功!"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 编辑地址信息
	 * */
	@RequestMapping(value ="/editor")
	public String editor(Page page,HttpServletRequest request) {
		boolean bl=StringUtils.isNumeric(request.getParameter("id"));
		if(bl==false || request.getParameter("id") == null || request.getParameter("id")==""){
			throw new DefiniteException("参数不正确！");
		}
		String id=request.getParameter("id");
		page.getParams().put("id",id);
		Address address=addressService.findAddressByID(page);
 		request.setAttribute("name", address.getReceiverName());
		request.setAttribute("phone", address.getReceiverPhone());
		request.setAttribute("addressDetail", address.getReceiverAddress());
		request.setAttribute("id",id);
		request.setAttribute("provinceName",address.getProvinceName()+"  ");
		request.setAttribute("cityName",address.getCityName()+"  ");
		request.setAttribute("status", address.getStatus());
		if(address.getCountryName() == null){
			request.setAttribute("countryName","");
		}else{
			request.setAttribute("countryName",address.getCountryName()+"  ");
		}
		System.out.println("商品id"+request.getParameter("goodsId"));
		if(!"".equals(request.getParameter("goodsId"))&&request.getParameter("goodsId")!=null){
			request.setAttribute("goodsId", request.getParameter("goodsId"));
			request.setAttribute("spec", request.getParameter("spec"));
			request.setAttribute("buyNum", request.getParameter("buyNum"));
		}
	    request.setAttribute("type", request.getParameter("type"));
		request.setAttribute("cityIDList",address.getProvinceID()+","+address.getCityID()+","+address.getCountryID());
		return "user/shippingAddress";
	}
	
	/**
	 * 删除地址信息
	 * */
	@RequestMapping(value = "/deleteAddress",method = { RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> deleteAddress(Page page, HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "删除个人地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			addressService.deleteAddress(page);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "删除成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 修改默认地址
	 * */
	@RequestMapping(value = "/updateDefault",method = { RequestMethod.POST})
	@ResponseBody
	public void updateDefault(Page page, HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "修改默认地址");
		try {
			User user=(User) request.getSession().getAttribute("sessionUser");
			page.getParams().put("userid", user.getId());
			addressService.updateDefault(page);
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
		}
		this.logAfter(logger);
	}
	
	/**
	 * 获取地理位置数据
	 * */
	@RequestMapping(value = "/getLocation",method = { RequestMethod.POST})
	@ResponseBody
	public List<Map<String, Object>> getLocation(){
		this.logBefore(logger, "获取地理位置数据");
			List<Map<String, Object>> list=addressService.getLocation();
			if(list!=null && list.size()>0){
				this.logAfter(logger);
				return list;
			}else{
				return null;
			}
	}
	
}
